import json
import logging
from decimal import Decimal

from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseNotFound, HttpResponseServerError, HttpResponseForbidden, JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.orders.models import OrderInfo, OrderGoods
from apps.users.models import Address
from config import settings
from utils.response_code import RETCODE

logger = logging.getLogger('django')

class OrderSettlementView(LoginRequiredMixin, View):
    """结算订单"""

    def get(self, request):
        # 获取当前登录用户对象
        user = request.user
        # 查询当前登录用户是否有收货地址
        try:
            addresses = Address.objects.filter(user=user, is_deleted=False)
            # 如果没有收货地址，那么就跳转到编辑收货地址页面
            if len(addresses) == 0:
                address_list = []
                context = {
                    'addresses': address_list
                }
                return render(request, 'user_center_site.html', context)
        except Exception as e:
            logger.error(e)
        # 从redis数据库中获取购物车数据  {b'1':b'1',b'2:b'2'}
        redis_conn = get_redis_connection('carts')
        redis_cart = redis_conn.hgetall('carts_%s' % user.id)
        # 从redis数据库中获取被勾选的商品sku_id  [b'1']
        redis_selected = redis_conn.smembers('selected_%s' % user.id)
        # 将被勾选的商品sku_id和数量组成一个新的数据
        new_cart_dict = {}
        for sku_id in redis_selected:
            new_cart_dict[int(sku_id)] = int(redis_cart[sku_id])
        # 通过sku模型类查询出在结算订单页面需要展示的商品sku
        sku_ids = new_cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        total_count = 0
        total_amount = Decimal(0.00)
        for sku in skus:
            # 遍历skus为每个sku补充count（数量）和amount（小计）
            sku.count = new_cart_dict[sku.id]
            sku.amount = sku.price * sku.count
            # # 累加数量和金额
            total_count += sku.count
            total_amount += sku.amount
        # 定义运费10元
        freight = Decimal(10.00)
        context = {
            'addresses': addresses,
            'skus': skus,
            'total_count': total_count,
            'total_amount': total_amount,
            'freight': freight,
            'payment_amount': total_amount + freight
        }
        return render(request, 'place_order.html', context=context)

class OrderCommentView(LoginRequiredMixin, View):
    """订单商品评价"""

    def get(self, request):
        """展示商品评价页面"""
        order_id = request.GET.get('order_id')  # 接收参数（订单编号）
        # 校验参数
        try:
            OrderInfo.objects.get(order_id=order_id, user=request.user)
        except OrderInfo.DoesNotExist:
            return HttpResponseNotFound('订单不存在')
        # 查询订单中未被评价的商品信息
        try:
            uncomment_goods = OrderGoods.objects.filter(order_id=order_id,
                                                        is_commented=False)
        except Exception:
            return HttpResponseServerError('订单商品信息出错')
        # 构造待评价商品数据
        uncomment_goods_list = []
        for goods in uncomment_goods:
            uncomment_goods_list.append({
                'order_id': goods.order.order_id, 'sku_id': goods.sku.id,
                'name': goods.sku.name, 'price': str(goods.price),
                'default_image_url': settings.STATIC_URL + 'images/goods/' + goods.sku.default_image.url + '.jpg',
                'comment': goods.comment, 'score': goods.score,
                'is_anonymous': str(goods.is_anonymous),
            })
        # 渲染模板
        context = {
            'uncomment_goods_list': uncomment_goods_list
        }
        return render(request, 'goods_judge.html', context)

    def post(self, request):
        json_dict = json.loads(request.body.decode())
        order_id = json_dict.get('order_id')
        sku_id = json_dict.get('sku_id')
        score = json_dict.get('score')
        comment = json_dict.get('comment')
        is_anonymous = json_dict.get('is_anonymous')
        # 校验参数
        if not all([order_id, sku_id, score, comment]):
            return HttpResponseForbidden('缺少必传参数')
        try:
            OrderInfo.objects.filter(order_id=order_id, user=request.user,
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
        except OrderInfo.DoesNotExist:
            return HttpResponseForbidden('参数order_id错误')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('参数sku_id错误')
        if is_anonymous:
            if not isinstance(is_anonymous, bool):
                return HttpResponseForbidden('参数is_anonymous错误')
        # 保存订单商品评价数据
        OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id,
                                  is_commented=False).update(
            comment=comment, score=score,
            is_anonymous=is_anonymous,
            is_commented=True
        )
        # 累计评论数据
        sku.comments += 1
        sku.save()
        sku.spu.comments += 1
        sku.spu.save()
        # 如果所有订单商品都已评价，则修改订单状态为已完成
        if OrderGoods.objects.filter(order_id=order_id,is_commented=False).count() == 0:
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '评价成功'})